package com.struts2.actions;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Namespaces;
import org.apache.struts2.convention.annotation.Result;

import com.opensymphony.xwork2.ActionSupport;


@Action(
		value="login", 
		results=
			{	@Result(name=Constants.WELCOME_TILES, location=Constants.WELCOME_TILES, type="tiles"),
				@Result(name=Constants.WELCOME_ACTION, location=Constants.WELCOME_ACTION, type="tiles" )
			}
)
@Namespaces(value={@Namespace("/login"),@Namespace("/")})
public class LoginAction extends ActionSupport {
	
	/**
	 * generated serialVersionUID
	 */
	private static final long serialVersionUID = -1577198318958806738L;
	private String username;
	private String password;
	private List<PartnershipLink> partners = new ArrayList<PartnershipLink>();
	private LegalEntity legalEntity;
	private Integer id;

	public String execute() {

		if(ServletActionContext.getRequest().getParameter("businessname") == null &&
				ServletActionContext.getRequest().getParameter("legal_entity_id") == null){
			partners = retrievePartnershipLinks();
			for(PartnershipLink pl: partners){
				pl.getPartner().setLink("<a href=\""+ServletActionContext.getRequest().getRequestURL()+"?businessname="+pl.getPartner().getBusinessname()+
						"&legal_entity_id="+pl.getPartner().getLegal_entity_id()+"\">"+pl.getPartner().getBusinessname()+"</a>");
			}
		}else{
			legalEntity = getLegalEntity(Integer.parseInt(ServletActionContext.getRequest().getParameter("legal_entity_id")));
		}
		
		/*if (this.username.equals("admin") 
				&& this.password.equals("admin123")) {
			return "success";
		} else {
			addActionError(getText("error.login"));
			return "error";
		}*/
		return Constants.WELCOME_TILES;
	}
	
	public String edit() {
		System.out.println("In edit ======== " + id);
		System.out.println("In edit ======== " + legalEntity);
		/*if (this.username.equals("admin") 
				&& this.password.equals("admin123")) {
			return "success";
		} else {
			addActionError(getText("error.login"));
			return "error";
		}*/
		if(id != null){
			legalEntity = getLegalEntity(id);
		}
		partners = retrievePartnershipLinks();
		return Constants.WELCOME_TILES;
	}
	
	public String delete() {
		System.out.println("in delete ============================ id = " + id);
		/*if (this.username.equals("admin") 
				&& this.password.equals("admin123")) {
			return "success";
		} else {
			addActionError(getText("error.login"));
			return "error";
		}*/
		if(id != null){			
			Integer result = deleteLegalEntity(id);
			if(result == 0){
				System.out.println("Legal Entity not deleted....");
			}else{
				System.out.println("Legal Entity deleted....");
			}
		}
		partners = retrievePartnershipLinks();
		System.out.println(partners);
		return Constants.WELCOME_TILES;
	}
	
	public String back() {
		partners = retrievePartnershipLinks();
		return Constants.WELCOME_TILES;
	}
	
	public String add() {
		partners = retrievePartnershipLinks();
		return Constants.WELCOME_TILES;
	}

	public static void main(String[] args){
		LoginAction action = new LoginAction();
		List<PartnershipLink> partners = action.retrievePartnershipLinks();
		for (PartnershipLink partnershipLink : partners) {
			System.out.println(partnershipLink.toString());
		}
	}
	
	private List<PartnershipLink> retrievePartnershipLinks(){
		List<PartnershipLink> partners = new ArrayList<PartnershipLink>();
		Connection con = null;
		ResultSet rs = null;
		PreparedStatement ps = null;
		try {
			con = getConnection();
			ps  = con.prepareStatement("select * from partnership_link");
			rs = ps.executeQuery();
			PartnershipLink pl = null;
			while(rs.next()){
				pl = new PartnershipLink();
				pl.setPartnership_link_id(rs.getInt("partnership_link_id"));
				pl.setPartner_start_date(rs.getDate("partner_start_date"));
				pl.setPartner_end_date(rs.getDate("partner_end_date"));
				pl.setPartner(getLegalEntity(rs.getInt("partner_id")));
				partners.add(pl);
			}
		} catch (Exception e) {
			System.out.println("Exception raised....");
			e.printStackTrace();
		}finally{
			closeResources(rs, ps, con);
		}
		return partners;
	}
	
	private LegalEntity getLegalEntity(int id){
		LegalEntity le = new LegalEntity();
		Connection con = null;
		ResultSet rs = null;
		PreparedStatement ps = null;
		try {
			con = getConnection();
			ps  = con.prepareStatement("select * from legal_entity where legal_entity_id=?");
			ps.setInt(1, id);
			rs = ps.executeQuery();
			while(rs.next()){
				le.setLegal_entity_id(rs.getInt("legal_entity_id"));
				le.setBusinessname(rs.getString("businessname"));
				le.setForenames(rs.getString("forenames"));
				le.setSurnames(rs.getString("surnames"));
			}
		} catch (Exception e) {
			System.out.println("Exception raised....");
			e.printStackTrace();
		}finally{
			closeResources(rs, ps, con);
		}
		return le;
	}
	
	private Integer deleteLegalEntity(int id){
		Connection con = null;
		PreparedStatement ps = null;
		Integer result = 0;
		try {
			con = getConnection();
			ps  = con.prepareStatement("delete from legal_entity where id = ?");
			ps.setInt(1, id);
			result = ps.executeUpdate();
		} catch (Exception e) {
			System.out.println("Exception raised....");
			e.printStackTrace();
		}finally{
			closeResources(null, ps, con);
		}
		return result;
	}
	
	private Connection getConnection(){
		Connection con = null;
		try {
			Class.forName("com.mysql.jdbc.jdbc2.optional.MysqlXAConnection");
			con = DriverManager.getConnection("jdbc:mysql://localhost:3306/gtrapp", "gtrmain", "tue01oct");
		} catch (ClassNotFoundException cnfe) {
			System.out.println("ClassNotFoundException raised....");
			cnfe.printStackTrace();
		} catch (Exception e) {
			System.out.println("Exception raised....");
			e.printStackTrace();
		}
		return con;
	}
	
	private void closeResources(ResultSet rs, PreparedStatement ps, Connection con){
		try {
			if(rs != null){rs.close();}
			if(ps != null){ps.close();}
			if(con != null){con.close();}
		} catch (Exception e) {
			System.out.println("Exception raised....");
			e.printStackTrace();
		}
	}
	
	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}
	
	public List<PartnershipLink> getPartners() {
		return partners;
	}

	public void setPartners(List<PartnershipLink> partners) {
		this.partners = partners;
	}

	public LegalEntity getLegalEntity() {
		return legalEntity;
	}

	public void setLegalEntity(LegalEntity legalEntity) {
		this.legalEntity = legalEntity;
	}
}
